package utils;

import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import java.util.prefs.BackingStoreException;
import java.util.prefs.Preferences;

import org.ini4j.Ini;
import org.ini4j.IniPreferences;
import org.ini4j.InvalidFileFormatException;

/**
 * parses settings.ini using ini4j
 * @author Mark
 *
 */
public class Settings {
	
	private final File INI_PATH = new File("settings.ini");
	private Preferences settings;
	
	public Settings(){
		if (!INI_PATH.isFile())
			StaticUtils.mustExitErrorMsg("can't locate: " + INI_PATH.getName() + "\nat: " + INI_PATH.getAbsolutePath(), 1);
		
		try {
			settings = new IniPreferences(new Ini(INI_PATH));
		} catch (InvalidFileFormatException e) {
			StaticUtils.mustExitErrorMsg(e.getMessage(), 1);
		} catch (IOException e) {
			StaticUtils.mustExitErrorMsg(e.getMessage(), 1);
		}
		
		
	}
	
	public void validTest(){
		if (!INI_PATH.isFile() || settings == null)
			StaticUtils.mustExitErrorMsg("can't locate: " + INI_PATH.getName() + "\nat: " + INI_PATH.getAbsolutePath(), 1);
	}
	
	/**
	 * getter
	 * @param setKey the required key (key=property)
	 * @param crashIfDoesnotExit to crash is key doesn't exist? (if settings node doesn't - will crash anyway)
	 * @return the property
	 */
	public String GetProperty(String setKey, boolean crashIfDoesnotExit){
		
		String[] allKey = null;
	
		try {
			allKey = settings.node("SETTINGS").keys();
		} catch (BackingStoreException e) {
			StaticUtils.mustExitErrorMsg(e.getMessage(), 1);
		}
		
		if(allKey == null || Arrays.binarySearch(allKey, setKey) == -1){
			if (crashIfDoesnotExit)
				StaticUtils.mustExitErrorMsg("Can't find in " + INI_PATH + " SETTINGS/" + setKey + "\nCan't Proceed", 2);
			else
				StaticUtils.errorMsg("Can't find in " + INI_PATH + " SETTINGS/" + setKey + "\nCan't Proceed");
		}
		
		return settings.node("SETTINGS").get(setKey.toLowerCase(), null);
	}
}
